package dao

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go-admin/base/utils"
	"strings"
)

var _ RoleModel = (*customRoleModel)(nil)

type (
	// RoleModel is an interface to be customized, add more methods here,
	// and implement the added methods in customRoleModel.
	RoleModel interface {
		roleModel
		FindAll(ctx context.Context) ([]*Role, error)
		FindOneByName(ctx context.Context, name string) (*Role, error)
		FindByRoleIds(ctx context.Context, roleIds []int64) ([]*Role, error)
		DeleteByRoleIds(ctx context.Context, roleIds []int64) error
	}

	customRoleModel struct {
		*defaultRoleModel
	}
)

func (c customRoleModel) DeleteByRoleIds(ctx context.Context, roleIds []int64) error {
	query := fmt.Sprintf("delete from %s where `id` in ( %s )", c.table, strings.Join(utils.GeneratePlaceholderByInt64(roleIds), ","))
	_, err := c.conn.ExecCtx(ctx, query, utils.ConvertToAny(roleIds)...)
	return err
}

func (c customRoleModel) FindAll(ctx context.Context) ([]*Role, error) {
	query := fmt.Sprintf("select %s from %s ", roleRows, c.table)
	var resp []*Role
	err := c.conn.QueryRowsCtx(ctx, &resp, query)
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (c customRoleModel) FindByRoleIds(ctx context.Context, roleIds []int64) ([]*Role, error) {
	//query := fmt.Sprintf("select %s from %s where `id` in ( ? )  ", roleRows, c.table)
	query := fmt.Sprintf("select %s from %s where `id` in ( %s )  ", roleRows, c.table, strings.Join(utils.GeneratePlaceholderByInt64(roleIds), ","))
	var resp []*Role
	err := c.conn.QueryRowsCtx(ctx, &resp, query, utils.ConvertToAny(roleIds)...)
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (c customRoleModel) FindOneByName(ctx context.Context, name string) (*Role, error) {
	query := fmt.Sprintf("select %s from %s where `name` = ? limit 1", roleRows, c.table)
	var resp Role
	err := c.conn.QueryRowCtx(ctx, &resp, query, name)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

// NewRoleModel returns a model for the database table.
func NewRoleModel(conn sqlx.SqlConn) RoleModel {
	return &customRoleModel{
		defaultRoleModel: newRoleModel(conn),
	}
}
